<?php
/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * This is a placeholder class.
 * Create the same file in app/Model/AppModel.php
 * Add your application-wide methods to the class, your models will inherit them.
 *
 * @package       Cake.Model
 */
class AppModel extends Model {
  private $imageTypes = array('image/gif'=>IMAGETYPE_GIF, 'image/jpeg'=>IMAGETYPE_JPEG, 'image/png'=>IMAGETYPE_PNG);

  function dateBefore($field, $comparisonField) {
    $retVal = false;
    $fieldValue = array_values($field);
    if(!empty($fieldValue[0]) && !empty($this->data[$this->name][$comparisonField])){
      //$date1 = DateTime::createFromFormat("m/d/Y", $fieldValue[0])->getTimestamp();
      //$date2 = DateTime::createFromFormat("m/d/Y", $this->data[$this->name][$comparisonField])->getTimestamp();
      $date1T = new DateTime($fieldValue[0]);
      $date2T = new DateTime($this->data[$this->name][$comparisonField]);
      $retVal = $date1T->getTimestamp() <= $date2T->getTimestamp();
    }
    return $retVal;
  }

  function validImageFormat($field, $validationRules) {
    $retVal = false;
    if (is_array($field)) {
      $fieldName = array_keys($field);
      if(empty($field[$fieldName[0]]['type']) && (isset($validationRules['allowEmpty']) &&  $validationRules['allowEmpty']) ) {
        $retVal = true;
      } elseif (!empty($fieldName) && isset($field[$fieldName[0]]['type'])) {
        $retVal = array_key_exists($field[$fieldName[0]]['type'], $this->imageTypes);
      }
    }
    return $retVal;
  }
  function validDateFormat($field) {
    $retVal = false;
    if (is_array($field)){
      $fieldName = array_keys($field);
      preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $field[$fieldName[0]], $retVal);
      $retVal = !empty($retVal);
    }
    return $retVal;
  }

  function beforeSave(){
    $model = $this->alias;
    $user = CakeSession::read('User');
    if(!empty($user)){
      //determining if this is insert or delete
      if(isset($this->id)) {
        //update
        $this->data[$model]['modified_by']=$user['User']['email'];
      } else {
        //insert
        $this->data[$model]['created_by']=$user['User']['email'];
      }
    }
    return true;
  }
}
